// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  data = event
  console.log('data : ', data)
  const $ = db.command.aggregate
  const _ = db.command
  data.date = new Date(data.date)
  let parmDateFmt = data.date.getTime()
  console.log("parmDateFmt : ", data.date)
  console.log("parmDateFmt : ", parmDateFmt)
  return db.collection('weight').aggregate()
    .match({
      dateTimeStamp: _.gte(parmDateFmt)
    })
    .group({
      _id: '$' + data.groupField,
      weight: $.first('$weight'),
      date: $.first('$date'),
      dateTime: $.first('$dateTime'),
      time: $.first('$time'),
      openid: $.first('$_openid')
    })
    .sort({
      dateTime: 1,
    })
    .skip(0)
    .limit(100) // 限制返回数量为 10 条
    .end({
      success: function (res) {
        console.log("分组成功: ", res)
        resolve && resolve(res)
      },
      fail: function (event) {
        reject && reject(event)
      }
    })
}